using Microsoft.AspNetCore.Mvc;
using ConsoleApi.Services;
using ConsoleApi.Services.Interfaces;

namespace ConsoleApi.Controllers;

/// <summary>
/// 天气API控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class WeatherApiController : ControllerBase
{
    private readonly IRealWeatherService _weatherService;
    private readonly ILogger<WeatherApiController> _logger;

    public WeatherApiController(IRealWeatherService weatherService, ILogger<WeatherApiController> logger)
    {
        _weatherService = weatherService;
        _logger = logger;
    }

    /// <summary>
    /// 获取城市天气信息
    /// </summary>
    [HttpGet("city/{city}")]
    public async Task<IActionResult> GetWeatherByCity(string city)
    {
        try
        {
            _logger.LogInformation("开始获取城市天气: {City}", city);
            var weatherData = await _weatherService.GetWeatherByCityAsync(city);
            
            _logger.LogInformation("成功获取城市天气: {City}, 温度: {Temp}°C", city, weatherData.Current?.Temp);
            
            return Ok(new
            {
                Success = true,
                Data = weatherData,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取城市天气失败: {City}", city);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    /// <summary>
    /// 通过坐标获取天气（使用城市名称模拟）
    /// </summary>
    [HttpGet("coordinates")]
    public async Task<IActionResult> GetWeatherByCoordinates(
        [FromQuery] double lat, 
        [FromQuery] double lon)
    {
        try
        {
            // 模拟通过坐标获取天气，实际调用城市天气接口
            var city = "未知城市"; // 这里可以根据坐标反查城市名称
            var weatherData = await _weatherService.GetWeatherByCityAsync(city);
            return Ok(new
            {
                Success = true,
                Data = weatherData,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "通过坐标获取天气失败: {Lat}, {Lon}", lat, lon);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    /// <summary>
    /// 获取天气预警
    /// </summary>
    [HttpGet("alerts/{city}")]
    public async Task<IActionResult> GetWeatherAlerts(string city)
    {
        try
        {
            var alerts = await _weatherService.GetWeatherAlertsAsync(city);
            return Ok(new
            {
                Success = true,
                Data = alerts,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取天气预警失败: {City}", city);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    /// <summary>
    /// 获取天气摘要
    /// </summary>
    [HttpGet("summary/{city}")]
    public async Task<IActionResult> GetWeatherSummary(string city)
    {
        try
        {
            var weatherData = await _weatherService.GetWeatherByCityAsync(city);
            var alerts = await _weatherService.GetWeatherAlertsAsync(city);
            
            var summary = new
            {
                City = city,
                CurrentWeather = weatherData.Current,
                Alerts = alerts,
                LastUpdated = weatherData.LastUpdated
            };
            
            return Ok(new
            {
                Success = true,
                Data = summary,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取天气摘要失败: {City}", city);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    /// <summary>
    /// 生产影响分析
    /// </summary>
    [HttpGet("production-impact")]
    public async Task<IActionResult> AnalyzeProductionImpact(
        [FromQuery] string city,
        [FromQuery] string activityType = "户外作业")
    {
        try
        {
            var weatherData = await _weatherService.GetWeatherByCityAsync(city);
            var alerts = await _weatherService.GetWeatherAlertsAsync(city);
            
            var analysis = new
            {
                City = city,
                ActivityType = activityType,
                CurrentWeather = weatherData.Current,
                Alerts = alerts,
                Recommendations = GenerateRecommendations(weatherData.Current, alerts, activityType),
                AnalysisTime = DateTime.Now
            };
            
            return Ok(new
            {
                Success = true,
                Data = analysis,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "分析生产影响失败: {City}, {Activity}", city, activityType);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    /// <summary>
    /// 多城市天气对比
    /// </summary>
    [HttpGet("compare")]
    public async Task<IActionResult> CompareCitiesWeather(
        [FromQuery] string cities)
    {
        try
        {
            var cityList = cities.Split(',').Select(c => c.Trim()).ToList();
            var comparison = new List<object>();
            
            foreach (var city in cityList.Take(5))
            {
                var weatherData = await _weatherService.GetWeatherByCityAsync(city);
                comparison.Add(new
                {
                    City = city,
                    CurrentWeather = weatherData.Current,
                    LastUpdated = weatherData.LastUpdated
                });
            }
            
            return Ok(new
            {
                Success = true,
                Data = comparison,
                Timestamp = DateTime.Now
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "对比城市天气失败: {Cities}", cities);
            return BadRequest(new
            {
                Success = false,
                Error = ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

    private List<string> GenerateRecommendations(dynamic? currentWeather, dynamic? alerts, string activityType)
    {
        var recommendations = new List<string>();
        
        if (currentWeather != null)
        {
            // 温度建议
            if (currentWeather.Temp > 35)
            {
                recommendations.Add("高温预警：温度超过35°C，建议暂停户外作业");
                recommendations.Add("调整工作时间，增加休息频率");
            }
            else if (currentWeather.Temp < 5)
            {
                recommendations.Add("低温预警：温度低于5°C，注意防寒保暖");
                recommendations.Add("加强保暖措施，注意设备防冻");
            }
            
            // 天气状况建议
            if (currentWeather.Text.Contains("雨"))
            {
                recommendations.Add("降雨天气，影响户外作业和物流运输");
                recommendations.Add("建议暂停户外作业，加强物流防护");
            }
            else if (currentWeather.Text.Contains("雪"))
            {
                recommendations.Add("降雪天气，道路湿滑，运输困难");
                recommendations.Add("建议暂停户外作业，注意交通安全");
            }
            else if (currentWeather.Text.Contains("雾"))
            {
                recommendations.Add("能见度低，影响运输和户外作业");
                recommendations.Add("建议降低作业速度，加强安全措施");
            }
        }
        
        // 活动类型特定建议
        if (activityType.Contains("户外"))
        {
            if (currentWeather?.Temp > 35 || currentWeather?.Temp < 5 || 
                currentWeather?.Text.Contains("雨") || currentWeather?.Text.Contains("雪"))
            {
                recommendations.Add("建议暂停户外作业");
                recommendations.Add("调整生产计划，选择适宜天气");
            }
        }
        else if (activityType.Contains("物流"))
        {
            if (currentWeather?.Text.Contains("雨") || currentWeather?.Text.Contains("雪") || 
                currentWeather?.Text.Contains("雾"))
            {
                recommendations.Add("天气影响物流运输，建议延迟发货");
                recommendations.Add("加强货物防护，注意运输安全");
            }
        }
        
        return recommendations;
    }
} 